<template>
  <div class="avatar" :style="{ width: avatarSize + 'px', height: avatarSize + 'px', borderRadius: avatarSize + 'px', overflow: 'hidden' }">
    <img :src="avatarPath" :width="avatarSize" :height="avatarSize"/>
  </div>
</template>

<script type="text/babel">
  import { Asset } from '../../libs/AssetsManager'
  import AssetComponent from './AssetComponent'
  import $ from 'jquery'
  export default {
    mixins: [ AssetComponent ],
    data () {
      return {
        avatarPath: ''
      }
    },
    props: {
      avatarSrc: {
        type: String
      },
      asset: {
        type: Asset
      },
      avatarSize: {
        type: Number
      }
    },
    ready: function () {
      this.avatarPath = this.getAvatarPath()
      var self = this
      $($(this.$el).children('img')[0]).load(function (event) {
        self.update($(this))
      })
    },
    watch: {
      'avatarPath': function (val, oldVal) {
        this.update($($(this.$el).children('img')[0]))
      },
      'avatarSize': function (val, oldVal) {
        this.update($($(this.$el).children('img')[0]))
      }
    },
    methods: {
      onAssetStateChanged: function (asset, currentState) {
        this.avatarPath = this.getAvatarPath()
      },
      getAvatarPath: function () {
        if (this.asset) {
          return this.asset.currentState()
        }
        return this.avatarSrc
      },
      update: function (img) {
        var imgWidth = img.width()
        var imgHeight = img.height()
        if (imgWidth && imgHeight) {
          var compSize = this.avatarSize
          img.css({
            top: (compSize - imgHeight) / 2 + 'px',
            left: (compSize - imgWidth) / 2 + 'px'
          })
        }
      }
    }
  }
</script>

<style scoped>
  .avatar {
    position: relative;
    top: 0;
    left: 0;
    transition: All 0.4s;
    -webkit-transition: All 0.4s;
    -moz-transition: All 0.4s;
    -o-transition: All 0.4s;
  }

  .avatar img {
    position: absolute;
    top: 0;
    left: 0;
    transition: All 0.4s;
    -webkit-transition: All 0.4s;
    -moz-transition: All 0.4s;
    -o-transition: All 0.4s;
  }
</style>